package com.sunshine.lnuplus.widget

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.widget.RemoteViews
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.model.WidgetData
import com.sunshine.lnuplus.service.UpdateWidgetService
import com.sunshine.lnuplus.ui.activity.SplashActivity
import com.sunshine.lnuplus.utils.DateUtils
import com.sunshine.lnuplus.utils.TagHelper
import es.dmoral.toasty.Toasty


/**
 * 参考
 * https://blog.csdn.net/liliang497/article/details/8308313
 * 感谢！
 */
class TimetableWidget : AppWidgetProvider(){

    private lateinit var widgetId: SharedPreferences
    private lateinit var edit: SharedPreferences.Editor
    private val REFRESH = "com.sunshine.lnuplus.REFRESH"

    override fun onUpdate(
        context: Context?,
        appWidgetManager: AppWidgetManager?,
        appWidgetIds: IntArray?
    ) {
        super.onUpdate(context, appWidgetManager, appWidgetIds)
        println("update")

        widgetId = context!!.getSharedPreferences("widget_id",Context.MODE_PRIVATE)
        edit = widgetId.edit()

        WidgetData.initData(context)
        WidgetData.initTimetableView(context)
        val thisWidget = ComponentName(context, TimetableWidget::class.java)
        val remoteViews = RemoteViews(context.packageName, R.layout.widget_timetable)
        val intent = Intent(context, UpdateWidgetService::class.java)

        appWidgetIds?.forEach {
            edit.putInt("$it", it)
            updateWidget(context, appWidgetManager, it, thisWidget, remoteViews, intent)
        }
        edit.apply()
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        super.onReceive(context, intent)
        when(intent?.action){
            REFRESH -> {
                widgetId = context!!.getSharedPreferences("widget_id",Context.MODE_PRIVATE)
//                println(WidgetData.lessonList)
//                println(intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID))
                WidgetData.initData(context)
                WidgetData.initTimetableView(context)
                widgetId.all.forEach {
                    val appWidgetId = it.value as Int
                    updateWidget(context, AppWidgetManager.getInstance(context), appWidgetId, ComponentName(context, TimetableWidget::class.java), RemoteViews(context.packageName, R.layout.widget_timetable), intent)
                }

                Toasty.info(context, "可能刷新了，我也没有证据").show()
            }
        }
    }

    override fun onDeleted(context: Context?, appWidgetIds: IntArray?) {
        super.onDeleted(context, appWidgetIds)

        widgetId = context!!.getSharedPreferences("widget_id",Context.MODE_PRIVATE)
        edit = widgetId.edit()
        appWidgetIds?.forEach {
            if(widgetId.contains("$it")){
                edit.remove("$it")
            }
        }
        edit.apply()
    }

    private fun updateWidget(
        context: Context?,
        appWidgetManager: AppWidgetManager?,
        appWidgetId: Int,
        thisWidget: ComponentName,
        remoteViews: RemoteViews,
        intent: Intent
    ) {
        //基本信息
        remoteViews.setTextViewText(R.id.text_date, "${DateUtils.month}月${DateUtils.day}日 周${DateUtils.getTodayOfWeekString(DateUtils.getTodayOfWeek())}")
        remoteViews.setTextViewText(R.id.text_week, "第${DateUtils.getThisWeek(WidgetData.widgetStyle!!.startMonth, WidgetData.widgetStyle!!.startDay)}周")

        val refreshIntent = Intent(context, TimetableWidget::class.java).setAction(REFRESH)
        val pendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, 0)
        remoteViews.setOnClickPendingIntent(R.id.iv_refresh, pendingIntent)

        //课程
        remoteViews.setRemoteAdapter(R.id.lesson_list_view, intent)
        val intent_start = Intent(context, SplashActivity::class.java)
        //需要在这指明要启动什么，在服务里不行
        val pendingIntentTemplate = PendingIntent.getActivity(context, TagHelper.TIMETABLEWIDGET, intent_start, PendingIntent.FLAG_CANCEL_CURRENT)
        remoteViews.setPendingIntentTemplate(R.id.lesson_list_view, pendingIntentTemplate)
        appWidgetManager?.updateAppWidget(thisWidget, remoteViews)
        AppWidgetManager.getInstance(context).notifyAppWidgetViewDataChanged(appWidgetId, R.id.lesson_list_view)
    }

}